package com.example.shoppingcart;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.shoppingcart.database.ShoppingCartDBHelper;
import com.example.shoppingcart.entity.CartInfo;
import com.example.shoppingcart.entity.GoodsInfo;
import com.example.shoppingcart.utils.ToastHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener {

    private ShoppingCartDBHelper dbHelper;

    // 购物车xml
    private LinearLayout ll_cart;
    // 购物车空状态xml
    private LinearLayout ll_empty_cart;
    // 购物车商品记录容器
    private LinearLayout ll_itemsContainer;
    // 结算总金额
    private TextView tv_totalAmount;
    // 购物车中商品数量
    private TextView tv_count;

    // 购物车中商品记录列表
    private List<CartInfo> cartRecordList;
    // 商品id和商品信息的映射
    private Map<Integer, GoodsInfo> goodsMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_shopping_cart);

        ll_cart = findViewById(R.id.ll_cart);
        ll_empty_cart = findViewById(R.id.ll_empty_cart);

        // 总金额
        tv_totalAmount = findViewById(R.id.tv_total_amount);

        // 购车中商品容器
        ll_itemsContainer = findViewById(R.id.ll_items_container);

        // 设置标题
        TextView tv_title = findViewById(R.id.tv_title);
        tv_title.setText("购物车");

        // 设置返回topbar返回点击事件
        findViewById(R.id.iv_back).setOnClickListener(this);
        // 设置点击清空购物车事件
        findViewById(R.id.btn_clear_cart).setOnClickListener(this);
        // 设置点击逛逛按钮事件
        findViewById(R.id.take_walk).setOnClickListener(this);
        // 设置点击结算按钮事件
        findViewById(R.id.btn_checkout).setOnClickListener(this);


        // 设置购物车商品数量
        tv_count = findViewById(R.id.tv_count);
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCountInCart));

        dbHelper = ShoppingCartDBHelper.getInstance(this);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();

        showCart();
    }

    // 渲染购车中所有的商品
    private void showCart() {
        // 先移除所有子元素-删除购物车中的内容
        ll_itemsContainer.removeAllViews();


        // 查询购物表，获取所有购物车中的商品
        cartRecordList = dbHelper.queryAllGoodsInCart();

        // 如果购物车为空
        if (cartRecordList.size() == 0) {

            // 隐藏购物车内容，显示空状态购物车
            ll_cart.setVisibility(View.INVISIBLE);
            ll_empty_cart.setVisibility(View.VISIBLE);

            return;
        }

        // 隐藏空状态购物车，显示购物车内容
        ll_cart.setVisibility(View.VISIBLE);
        ll_empty_cart.setVisibility(View.INVISIBLE);

        // 根据购物车记录id，查询每条记录的商品信息
        for (CartInfo record : cartRecordList) {
            GoodsInfo goodsInfo = dbHelper.queryGoodsInfoById(record.goodsId);
            goodsMap.put(goodsInfo.id, goodsInfo);

            // activity_cart_goods_record.xml对象
            View view = LayoutInflater.from(this).inflate(R.layout.activity_cart_goods_record, null);
            // 设置图片
            ImageView iv_goods_image = view.findViewById(R.id.iv_goods_image);
            iv_goods_image.setImageURI(Uri.parse(goodsInfo.picPath));
            // 设置名称
            TextView goodsName = view.findViewById(R.id.goods_name);
            goodsName.setText(goodsInfo.name);
            // 设置介绍
            TextView goodsDesc = view.findViewById(R.id.goods_desc);
            goodsDesc.setText(goodsInfo.description);
            // 设置数量
            TextView goodsCount = view.findViewById(R.id.goods_count);
            goodsCount.setText(String.valueOf(record.count));
            // 设置单价
            TextView goodsPrice = view.findViewById(R.id.goods_price);
            goodsPrice.setText(String.valueOf((int) goodsInfo.price));
            // 设置总价
            TextView goodsAmount = view.findViewById(R.id.goods_amount);
            goodsAmount.setText(String.valueOf((int) (record.count * goodsInfo.price)));

            // 给购车商品条目xml添加点击事件，长按删除
            view.setOnLongClickListener(v -> {
                Log.d("zhoutao", "长按: ");
                // 弹窗
                AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
                builder.setMessage("是否从购物车删除 " + goodsInfo.name + "？");
                // 点击确定
                builder.setPositiveButton("是", (dialog, which) -> {
                    // 移除当前购物车商品条目xml视图
                    ll_itemsContainer.removeView(view);
                    // 从购物车表中删除该条记录
                    deleteRecordFromCartTable(record);
                });
                // 点击取消
                builder.setNegativeButton("否", null);
                builder.create().show();
                return true;
            });

            // 给购车商品条目xml添加点击事件，点击跳转详情页面
            view.setOnClickListener(v -> {
                Intent intent = new Intent(ShoppingCartActivity.this, GoodsDetial.class);
                intent.putExtra("goods_id", goodsInfo.id);
                startActivity(intent);
            });

            // 购物车商品容器中插入该条商品
            ll_itemsContainer.addView(view);
        }

        setTotalPrice();


    }

    private void deleteRecordFromCartTable(CartInfo record) {
        // 购物车总数中减去该条记录的数量
        MyApplication.getInstance().goodsCountInCart -= record.count;
        // 从购物车表中删除该条记录
        dbHelper.deleteCartInfoByGoodsId(record.goodsId);

        //从缓存中删除该条记录
        CartInfo removed = null;
        for (CartInfo cardInfo : cartRecordList) {
            if (cardInfo.id == record.id) {
                removed = cardInfo;
            }
        }
        cartRecordList.remove(removed);

        // 重新设置购物车商品数量
        setCount();
        ToastHelper.show(this, "已从购物车中删除" + goodsMap.get(record.goodsId).name);

        // 设置结算金额
        setTotalPrice();
    }

    private void setCount() {
        // 设置购物车商品数量
        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCountInCart));
        if (MyApplication.getInstance().goodsCountInCart == 0) {
            // 如果购物车为空，则显示空状态
            ll_cart.setVisibility(View.INVISIBLE);
            ll_empty_cart.setVisibility(View.VISIBLE);
            ll_cart.removeAllViews();
        } else {
            ll_cart.setVisibility(View.VISIBLE);
            ll_empty_cart.setVisibility(View.INVISIBLE);
        }

    }

    // 设置结算金额
    private void setTotalPrice() {
        int amount = 0;
        for (CartInfo record : cartRecordList) {
            GoodsInfo goods = goodsMap.get(record.goodsId);

            amount += goods.price * record.count;
        }

        tv_totalAmount.setText(String.valueOf(amount));
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        // 点击返回
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.take_walk) {
            // 点击逛逛
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (id == R.id.btn_checkout) {
            // 点击结算
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("非常抱歉");
            builder.setMessage("尊敬的客观，支付功能尚未开通");
            builder.setPositiveButton("好的", null);
            builder.create().show();
        } else if (id == R.id.btn_clear_cart) {
            // 点击清空
            // 清空购物车表
            dbHelper.clearCartInfo();
            // 设置全局购物车商品数量
            MyApplication.getInstance().goodsCountInCart = 0;
            // 设置topbar显示数量
            setCount();
            ToastHelper.show(this, "购物车已清空");
        }
    }
}